﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Database.infrastructure
{
    /// <summary>
    /// 仓储类，操作
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class RepositoryBase<T> : IRepositoryBase<T> where T : class
    {
        private readonly IDatabaseFactory _databaseFactory;
        private readonly IDbSet<T> _dbSet;

        public RepositoryBase(IDatabaseFactory factory)
        {
            _databaseFactory = factory;
            _dbSet = factory.Get<T>();
        }

        public void Add(T entity)
        {
            _dbSet.Add(entity);
        }

        public void Update(T entity)
        {
            _dbSet.Attach(entity);
            _databaseFactory._dbContext.Entry(entity).State = EntityState.Modified;
        }

        public IQueryable<T> GetAll()
        {
            return GetAll(a => true);
        }

        public IQueryable<T> GetAll(Expression<Func<T, bool>> @where)
        {
            return _dbSet.Where(where);
        }

        public void Remove(T entity)
        {
            _dbSet.Remove(entity);
        }

        public void Remove(Expression<Func<T, bool>> @where)
        {
            foreach (T item in GetAll(where))
                Remove(item);
        }

        public void Save(object id, T entity)
        {
            if (id == null) Add(entity);
            else Update(entity);
        }
    }
}
